//
//  ZCPreparationViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/3.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCPreparationViewController.h"
#import "UWRQViewController.h"
#import "ZCPutInStorageTableViewCell.h"
#import "ZCPreparationModel.h"
#import "ZCPreparationDetailViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCPreparationTableViewCell.h"
#import "ZCPreparationTaskViewController.h"

static NSString *prepareCellID = @"ZCPutInStorageTableViewCell";
static NSString *prepareCellNewID = @"ZCPreparationTableViewCell";

@interface ZCPreparationViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchBarDelegate, uwRQDelegate, ZCTaskTitleViewDelegate>

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) ZCTaskTitleView *taskView;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) BOOL isStart;
@property (nonatomic, strong) ZCPreparationListModel *listModel;

@end

@implementation ZCPreparationViewController
#pragma mark - 懒加载
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(112))];
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 56)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"请输入指令号/板车号";
    }
    return _searchBar;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = ZCColor(0x000000, 0.05);
    }
    return _lineView;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (UITableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + space(192), SCREENWIDTH, SCREENHEIGHT - 64 - space(192)) style:UITableViewStyleGrouped];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTableView.showsVerticalScrollIndicator = NO;
        _listTableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _listTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _listTableView.estimatedRowHeight = 0;
            _listTableView.estimatedSectionFooterHeight = 0;
            _listTableView.estimatedSectionHeaderHeight = 0;
        }
        [_listTableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:prepareCellID];
        [_listTableView registerClass:[ZCPreparationTableViewCell class] forCellReuseIdentifier:prepareCellNewID];
        _listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _listTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _listTableView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.title = @"备料任务";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.searchView];
    [self.searchView addSubview:self.searchBar];
    [self.searchView addSubview:self.lineView];
   
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    self.taskView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64 + space(112), SCREENWIDTH, space(80))];
    self.taskView.delegate = self;
    self.taskView.titleArray = @[@"待领取",@"执行中"];
    [self.view addSubview:self.taskView];
    self.status = @"10";
    self.isStart = NO;
    [self.view addSubview:self.listTableView];
    [self updateViewConstraints];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.listArray removeAllObjects];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
}

#pragma mark - 网络请求
- (void)loadData {
    self.currentPage = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [param setObject:houseId forKey:@"condition[houseId]"];
    [param setObject:self.searchBar.text.length > 0 ? self.searchBar.text : @"" forKey:@"condition[plateNo]"];
    [param setObject:@(self.currentPage) forKey:@"current"];
    [param setObject:@(10) forKey:@"size"];
    [param setObject:self.status forKey:@"condition[searchLabel]"];
    
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:PrepareList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.listArray removeAllObjects];
                weakSelf.listModel = [ZCPreparationListModel yy_modelWithJSON:responseObject[@"data"]];
                [weakSelf.listArray addObjectsFromArray:weakSelf.listModel.records];
                [weakSelf.listTableView reloadData];
                if (weakSelf.listModel.records.count < 10) {
                    [weakSelf.listTableView.mj_footer resetNoMoreData];
                }
                [weakSelf.listTableView.mj_header endRefreshing];
            }else {
                [weakSelf.listTableView.mj_header endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.listTableView.mj_header endRefreshing];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

- (void)loadMoreData {
    self.currentPage++;
    if (self.currentPage <= [self.listModel.pages integerValue]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
        [param setObject:houseId forKey:@"condition[houseId]"];
        [param setObject:self.searchBar.text.length > 0 ? self.searchBar.text : @"" forKey:@"condition[plateNo]"];
        [param setObject:@(self.currentPage) forKey:@"current"];
        [param setObject:@(10) forKey:@"size"];
        [param setObject:self.status forKey:@"condition[searchLabel]"];
        
        self.hud.mode = MBProgressHUDModeIndeterminate;
        self.hud.label.text = @"";
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:PrepareList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [weakSelf.hud hideAnimated:YES];
                    weakSelf.listModel = [ZCPreparationListModel yy_modelWithJSON:responseObject[@"data"]];
                    [weakSelf.listArray addObjectsFromArray:weakSelf.listModel.records];
                    [weakSelf.listTableView reloadData];
                    if (weakSelf.listModel.records.count < 10) {
                        [weakSelf.listTableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.listTableView.mj_footer endRefreshing];
                    }
                }else {
                    [weakSelf.listTableView.mj_footer endRefreshing];
                    weakSelf.currentPage--;
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [weakSelf.listTableView.mj_footer endRefreshing];
                weakSelf.currentPage--;
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }else {
        [self.listTableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"待领取"]) {
        if ([self.status integerValue] != 10) {
            self.status = @"10";
            self.isStart = NO;
        }
        [self loadData];
    }else if ([title isEqualToString:@"执行中"]) {
        if ([self.status integerValue] != 20) {
            self.status = @"20";
            self.isStart = YES;
        }
        [self loadData];
    }
    
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self loadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (self.listArray.count != 0) {
        [self.listArray removeAllObjects];
        [self.listTableView reloadData];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPreparationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:prepareCellNewID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZCPreparationTaskInfoModel *infoModel = self.listArray[indexPath.section];
    cell.listModel = infoModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(400);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPreparationTaskViewController *taskVC = [[ZCPreparationTaskViewController alloc] init];
    taskVC.isCheck = self.isStart;
    ZCPreparationTaskInfoModel *infoModel = self.listArray[indexPath.section];
    taskVC.taskInfoId = infoModel.taskInfoId;
    [self.navigationController pushViewController:taskVC animated:YES];
    
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.searchView.mas_left);
        make.right.equalTo(weakSelf.searchView.mas_right);
        make.bottom.equalTo(weakSelf.searchView.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    
}

@end
